layui.config({
    base: '/plugins/layui-export/',
}).use(['form', 'table', 'laypage'], function () {

    var form = layui.form,
        user = {
            data: {
                pageData: {
                    count: 0,
                    pageNum: 1,
                    pageSize: 10
                },
                userRoleIds: []
            },
            start: function () {
                this.onLoad()
                this.bindEvent()
            },
            onLoad: function () {
                this.loadTableData()
            },
            bindEvent: function () {

                var _this = this

                $('#user_search_btn').click(function () {
                    _this.data.pageData.count = 0
                    _this.data.pageData.pageNum = 1
                    _this.loadTableData()
                })

                $('#user_name_search_text').keyup(function (e) {
                    if (e.keyCode == 13) {
                        _this.data.pageData.count = 0
                        _this.data.pageData.pageNum = 1
                        _this.loadTableData()
                    }
                })

                $('#reset_search_btn').click(function () {
                    $('#user_name_search_text').val('')
                })

                $('#add_user_btn').click(function () {

                    sinoUtil.sendHttp(sinoUtil.httpPrefix + '/api/role/queryRoles', 'get', {
                        roleName: '',
                        pageNum: 1,
                        pageSize: 10000
                    }, function (res) {

                        if (res.status == 0) {

                            $('#role_content').append(_this.generateRoles(res.data.list))

                            form.render()

                            layer.open({
                                type: 1,
                                content: $('#user_form_content'),
                                area: ['900px', '650px'],
                                btn: ['提交', '取消'],
                                btnAlign: 'c',
                                shadeClose: true,
                                maxmin: true,
                                success: function (layero, index) {
                                },
                                yes: function (index, layero) {
                                    if (_this.validateForm()) {

                                        _this.data.index = sinoUtil.loading()

                                        _this.data.userRoleIds = []

                                        $.each($('#role_content input:checkbox:checked'), function () {
                                            _this.data.userRoleIds.push($.trim($(this).val()));
                                        })

                                        sinoUtil.sendHttp(sinoUtil.httpPrefix + '/api/user/addUserInfo', 'post', {
                                            // companyId: $.trim($('#user_company_id').val()),
                                            // userDepartId: $.trim($('#user_depart_id').val()) === 'default' ? null : $.trim($('#user_depart_id').val()),
                                            // isManager: $.trim($('#user_is_manager').val()),
                                            // bandOaAccount: $.trim($('#user_band_oa_account').val()),
                                            userName: $.trim($('#user_name').val()),
                                            userMail: $.trim($('#user_email').val()),
                                            userPasswd: $.trim($('#user_password').val()),
                                            userPhone: $.trim($('#user_phone').val()),
                                            removeTag: $.trim($('#remove_tag').val()),
                                            remark: $.trim($('#remark').val()),
                                            roleIds: _this.data.userRoleIds.join(',')
                                        }, function (res) {
                                            if (res.status == 0) {
                                                layer.close(index)
                                                sinoUtil.stopLoadingAndShowResult(_this.data.index, 1, '新增成功')
                                                _this.loadTableData()
                                            } else if (res.status == 10 || res.status == 11) {
                                                window.parent.location.href = '/system/login'
                                            } else {
                                                sinoUtil.stopLoadingAndShowResult(_this.data.index, 2, res.msg)
                                            }
                                        }, function (error) {
                                            layer.close(index)
                                            sinoUtil.stopLoadingAndShowResult(_this.data.index, 2, '新增失败')
                                        }, false)
                                    }
                                },
                                end: function () {
                                    // $('#user_company_id').removeClass("error").next("p").remove().val('default')
                                    // $('#user_depart_id').empty()
                                    // $('#user_is_manager').removeClass("error").next("p").remove().val('default')
                                    // $('#user_band_oa_account').val('')
                                    $('#user_name').val('').removeClass("error").next("p").remove()
                                    $('#user_email').val('').removeClass("error").next("p").remove()
                                    $('#user_phone').val('').removeClass("error").next("p").remove()
                                    $('#user_password').val('').removeClass("error").next("p").remove()
                                    $('#user_password_repeat').val('').removeClass("error").next("p").remove()
                                    $('#remark').val('')
                                    $('#remove_tag').val('0')
                                    $('#role_content').empty()
                                }
                            })
                        } else if (res.status == 10 || res.status == 11) {
                            window.parent.location.href = '/system/login'
                        }
                    }, function (error) {
                        layer.msg('拉取角色信息失败')
                    }, false)

                })

            },
            loadTableData: function () {

                var _this = this

                sinoUtil.sendHttp(sinoUtil.httpPrefix + '/api/user/qryUsersForPT', 'get', {
                    userName: $.trim($('#user_name_search_text').val()),
                    pageNum: _this.data.pageData.pageNum,
                    pageSize: _this.data.pageData.pageSize
                }, function (res) {
                    if (res.status == 0) {
                        layui.use('table', function () {
                            var table = layui.table
                            table.render({
                                elem: '#user_table'
                                , height: 352
                                , url: ''
                                , data: res.data.list
                                , page: false
                                , cols: [[
                                    {
                                        field: 'userName',
                                        title: '用户名',
                                        width: '20%',
                                        minWidth: 200,
                                        align: 'center'
                                    },
                                    {
                                        field: 'userMail',
                                        title: '邮箱',
                                        width: '20%',
                                        minWidth: 200,
                                        align: 'center'
                                    },
                                    {
                                        field: 'userPhone',
                                        title: '电话',
                                        width: '20%',
                                        minWidth: 200,
                                        align: 'center'
                                    },
                                    {
                                        field: 'removeTag',
                                        title: '状态',
                                        width: '10%',
                                        minWidth: 100,
                                        align: 'center'
                                    },
                                    {
                                        field: 'remark',
                                        title: '备注',
                                        width: '20%',
                                        minWidth: 200,
                                        align: 'center'
                                    },
                                    {
                                        title: '操作',
                                        fixed: 'right',
                                        width: '10%',
                                        align: 'center',
                                        minWidth: 100,
                                        toolbar: '#user_table_tool_bar'
                                    }
                                ]]
                                , text: {
                                    none: '暂无相关数据'
                                },
                                done: function (res, page, count) {
                                    $("[data-field='removeTag']").children().each(function () {
                                        if ($(this).text() == '0') {
                                            $(this).text("启用")
                                        } else {
                                            $(this).text("禁用")
                                        }
                                    })
                                }
                            })
                            table.on('tool(user)', function (obj) {
                                var layEvent = obj.event;
                                if (layEvent === 'editUserInfo') {
                                    _this.editRowData(obj.data)
                                }
                                else if (layEvent === 'delUserInfo') {
                                    _this.delRowData(obj.data.userId)
                                }

                            })
                        })
                        _this.data.pageData.count = res.data.total
                        _this.loadPageContent()

                    } else if (res.status == 11 || res.status == 10) {
                        window.parent.location.href = '/system/login'
                    } else {
                        _this.data.pageData.count = 0
                        _this.data.pageData.pageNum = 1
                        layer.msg(res.msg)
                    }
                }, function (error) {
                    _this.data.pageData.count = 0
                    _this.data.pageData.pageNum = 1
                    layer.msg('哪里出错了')
                }, false)

            },
            loadPageContent: function () {

                var _this = this

                layui.use('laypage', function () {

                    var laypage = layui.laypage

                    laypage.render({
                        elem: 'user_page_content'
                        , count: _this.data.pageData.count
                        , limit: _this.data.pageData.pageSize
                        , curr: _this.data.pageData.pageNum
                        , jump: function (obj, first) {
                            if (!first) {
                                _this.data.pageData.pageNum = obj.curr
                                _this.data.pageData.pageSize = obj.limit
                                _this.loadTableData()
                            }
                        }
                    })
                })

            },
            generateRoles: function (roleArr, checkedArr) {

                var roleStr = ''
                var flag = false

                for (var i = 0, iLength = roleArr.length; i < iLength; i++) {

                    if (checkedArr) {
                        for (var j = 0, jLength = checkedArr.length; j < jLength; j++) {
                            if (roleArr[i].roleId == checkedArr[j]) {
                                flag = true
                                break
                            }
                        }
                        if (flag) {
                            roleStr += '<input type="checkbox" value="' + roleArr[i].roleId + '" title="' + roleArr[i].roleName + '" checked>'
                        } else {
                            roleStr += '<input type="checkbox" value="' + roleArr[i].roleId + '" title="' + roleArr[i].roleName + '">'
                        }
                        flag = false
                    } else {
                        roleStr += '<input type="checkbox" value="' + roleArr[i].roleId + '" title="' + roleArr[i].roleName + '">'
                    }
                }
                return roleStr
            },
            validateForm: function () {
                if (!sinoUtil.validate($('#user_name').val(), 'require')) {
                    sinoUtil.validateAndChangeClass('#user_name', false, "请填写用户名")
                    return false
                } else {
                    sinoUtil.validateAndChangeClass('#user_name', true, "校验通过")
                }
                // if (!sinoUtil.validate($('#user_email').val(), 'require')) {
                //     sinoUtil.validateAndChangeClass('#user_email', false, "请填写用户邮箱")
                //     return false
                // } else {
                //     sinoUtil.validateAndChangeClass('#user_email', true, "校验通过")
                // }
                if (!sinoUtil.validate($('#user_email').val(), 'email')) {
                    sinoUtil.validateAndChangeClass('#user_email', false, "请填写正确格式的用户邮箱")
                    return false
                } else {
                    sinoUtil.validateAndChangeClass('#user_email', true, "校验通过")
                }
                // if (!sinoUtil.validate($('#user_phone').val(), 'require')) {
                //     sinoUtil.validateAndChangeClass('#user_phone', false, "请填写用户手机号")
                //     return false
                // } else {
                //     sinoUtil.validateAndChangeClass('#user_phone', true, "校验通过")
                // }
                if (!sinoUtil.validate($('#user_phone').val(), 'phone')) {
                    sinoUtil.validateAndChangeClass('#user_phone', false, "请填写正确格式的用户手机号")
                    return false
                } else {
                    sinoUtil.validateAndChangeClass('#user_phone', true, "校验通过")
                }
                if (!sinoUtil.validate($('#user_password').val(), 'require')) {
                    sinoUtil.validateAndChangeClass('#user_password', false, "请填写6~15位的用户密码")
                    return false
                } else {
                    sinoUtil.validateAndChangeClass('#user_password', true, "校验通过")
                }
                if ($('#user_password').val().length < 6 || $('#user_password').val().length > 15) {
                    sinoUtil.validateAndChangeClass('#user_password', false, "用户密码少于6位或大于15位,请重新填写")
                    return false
                } else {
                    sinoUtil.validateAndChangeClass('#user_password', true, "校验通过")
                }
                if ($('#user_password_repeat').val() !== $('#user_password').val()) {
                    sinoUtil.validateAndChangeClass('#user_password_repeat', false, "两次密码输入不一致,请重新填写")
                    return false
                } else {
                    sinoUtil.validateAndChangeClass('#user_password_repeat', true, "校验通过")
                }
                return true
            },
            delRowData: function (staffId) {

                var _this = this

                layer.confirm('数据删除后将不可恢复,确定要删除吗?', function (index) {
                    layer.close(index)
                    _this.data.index = sinoUtil.loading()
                    sinoUtil.sendHttp(sinoUtil.httpPrefix + '/api/user/deleteUserInfo', 'post', {
                        userIds: staffId
                    }, function (res) {
                        if (res.status == 0) {
                            sinoUtil.stopLoadingAndShowResult(_this.data.index, 1, '删除成功')
                            _this.data.pageData.count = 0
                            _this.data.pageData.pageNum = 1
                            _this.loadTableData()
                        } else if (res.status == 10 || res.status == 11) {
                            sinoUtil.stopLoadingAndShowResult(_this.data.index, 2, '')
                            window.parent.location.href = '/system/login'
                        } else {
                            sinoUtil.stopLoadingAndShowResult(_this.data.index, 2, res.msg)
                        }
                    }, function (error) {
                        sinoUtil.stopLoadingAndShowResult(_this.data.index, 2, '删除失败')
                    }, false)
                })
            },
            editRowData: function (rowData) {

                var _this = this

                sinoUtil.sendHttp(sinoUtil.httpPrefix + '/api/role/queryRoles', 'get', {
                    roleName: '',
                    pageNum: 1,
                    pageSize: 10000
                }, function (res) {

                    if (res.status == 0) {

                        $('#edit_role_content').append(_this.generateRoles(res.data.list, rowData.userRoleIds))

                        // var loadingIndex = sinoUtil.loading();
                        // sinoUtil.sendHttp(sinoUtil.httpPrefix + "/api-system/getDepartmentByCompanyIdForPT", "POST", {companyId: rowData.companyId}, function (res) {
                        //     if (res.status == 0) {
                        //         $("#user_edit_depart_id").empty().append("<option value=\"default\">请选部门</option>");
                        //         for (var i = 0; i < res.data.length; i++) {
                        //             var option = document.createElement("option");
                        //             option.setAttribute("value", res.data[i].departId);
                        //             option.innerHTML = res.data[i].departName;
                        //             $("#user_edit_depart_id").append(option);
                        //         }
                        //         $("#user_edit_depart_id").val(rowData.userDepartId)
                        //         form.render();
                        //         sinoUtil.stopLoadingAndShowResult(loadingIndex, 1);
                        //     } else if (res.status == 10 || res.status == 11) {
                        //         window.parent.location.href = "/system/login";
                        //     } else {
                        //         sinoUtil.stopLoadingAndShowResult(loadingIndex, 2, "部门信息获取失败，请刷新重试");
                        //     }
                        // }, function (error) {
                        //     sinoUtil.stopLoadingAndShowResult(loadingIndex, 2, "发生未知错误，请刷新重试");
                        // }, false);

                        // $('#user_edit_is_manager').val(rowData.isManager)
                        // $('#user_edit_band_oa_account').val(rowData.bandOaAccount)
                        $('#user_edit_name').val(rowData.userName)
                        $('#user_edit_email').val(rowData.userMail)
                        $('#user_edit_phone').val(rowData.userPhone)
                        $('#edit_remark').val(rowData.remark)
                        $('#edit_remove_tag').val(rowData.removeTag)

                        form.render()

                        layer.open({
                            type: 1,
                            content: $('#user_edit_form_content'),
                            area: ['800px', '600px'],
                            btn: ['提交', '取消'],
                            btnAlign: 'c',
                            shadeClose: true,
                            maxmin: true,
                            success: function (layero, index) {
                            },
                            yes: function (index, layero) {
                                if (_this.validateEditForm()) {

                                    _this.data.index = sinoUtil.loading()

                                    _this.data.userRoleIds = []

                                    $.each($('#edit_role_content input:checkbox:checked'), function () {
                                        _this.data.userRoleIds.push($.trim($(this).val()));
                                    })

                                    sinoUtil.sendHttp(sinoUtil.httpPrefix + '/api/user/editUserInfo', 'post', {
                                        userId: rowData.userId,
                                        // userDepartId: $.trim($('#user_edit_depart_id').val()) === 'default' ? null : $.trim($('#user_edit_depart_id').val()),
                                        // isManager: $.trim($('#user_edit_is_manager').val()),
                                        // bandOaAccount: $.trim($('#user_edit_band_oa_account').val()),
                                        userName: $.trim($('#user_edit_name').val()),
                                        userPhone: $.trim($('#user_edit_phone').val()),
                                        removeTag: $.trim($('#edit_remove_tag').val()),
                                        remark: $.trim($('#edit_remark').val()),
                                        roleIds: _this.data.userRoleIds.join(',')
                                    }, function (res) {
                                        if (res.status == 0) {
                                            layer.close(index)
                                            sinoUtil.stopLoadingAndShowResult(_this.data.index, 1, '修改成功')
                                            _this.loadTableData()
                                        } else if (res.status == 10 || res.status == 11) {
                                            window.parent.location.href = '/system/login'
                                        } else {
                                            sinoUtil.stopLoadingAndShowResult(_this.data.index, 2, res.msg)
                                        }
                                    }, function (error) {
                                        layer.close(index)
                                        sinoUtil.stopLoadingAndShowResult(_this.data.index, 2, '修改失败')
                                    }, false)
                                }
                            },
                            end: function () {
                                // $('#user_edit_depart_id').empty()
                                // $('#user_edit_is_manager').val('').removeClass("error").next("p").remove()
                                // $('#user_edit_band_oa_account').val('')
                                $('#user_edit_name').val('').removeClass("error").next("p").remove()
                                $('#user_edit_email').val('').removeClass("error").next("p").remove()
                                $('#user_edit_phone').val('').removeClass("error").next("p").remove()
                                $('#edit_remark').val('')
                                $('#edit_remove_tag').val('0')
                                $('#edit_role_content').empty()
                            }
                        })
                    } else if (res.status == 10 || res.status == 11) {
                        window.parent.location.href = '/system/login'
                    }
                }, function (error) {
                    layer.msg('拉取角色信息失败')
                }, false)
            },
            validateEditForm: function () {

                // if (!sinoUtil.validate($('#user_edit_depart_id').val() == 'default' ? null : $('#user_edit_depart_id').val(), 'require')) {
                //     sinoUtil.validateAndChangeClass('#user_edit_depart_id', false, "请选择部门")
                //     return false
                // } else {
                //     sinoUtil.validateAndChangeClass('#user_edit_depart_id', true, "校验通过")
                // }
                //
                // if (!sinoUtil.validate($('#user_edit_is_manager').val() == 'default' ? null : $('#user_edit_is_manager').val(), 'require')) {
                //     sinoUtil.validateAndChangeClass('#user_edit_is_manager', false, "请选择是否为部门管理员")
                //     return false
                // } else {
                //     sinoUtil.validateAndChangeClass('#user_edit_is_manager', true, "校验通过")
                // }
                //
                // if ((!$('#user_edit_depart_id').val() || $('#user_edit_depart_id').val() == 'default') && $('#user_edit_is_manager').val() == 0) {
                //     sinoUtil.validateAndChangeClass('#user_edit_is_manager', false, "未选部门，不能设为管理员")
                //     return false
                // } else {
                //     sinoUtil.validateAndChangeClass('#user_edit_is_manager', true, "校验通过")
                // }

                if (!sinoUtil.validate($('#user_edit_name').val(), 'require')) {
                    sinoUtil.validateAndChangeClass('#user_edit_name', false, "请填写用户名")
                    return false
                } else {
                    sinoUtil.validateAndChangeClass('#user_edit_name', true, "校验通过")
                }

                if (!sinoUtil.validate($('#user_edit_phone').val(), 'require')) {
                    sinoUtil.validateAndChangeClass('#user_edit_phone', false, "请填写用户手机号")
                    return false
                } else {
                    sinoUtil.validateAndChangeClass('#user_edit_phone', true, "校验通过")
                }

                if (!sinoUtil.validate($('#user_edit_phone').val(), 'phone')) {
                    sinoUtil.validateAndChangeClass('#user_edit_phone', false, "请填写正确格式的用户手机号")
                    return false
                } else {
                    sinoUtil.validateAndChangeClass('#user_edit_phone', true, "校验通过")
                }

                return true
            }
        }

    $(function () {
        user.start()
    })

})